import React,{Component} from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import {Form, Input, Button, message } from 'antd';
import { createSaveUserInfoAction} from '../../redux/action_creators/login_action';
import {reqLogin,reqTeacherLogin} from '../../api';
import './login.less';
import logo from '../../static/images/logo.png';

const layout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 16,
    },
  };
const tailLayout = {
    wrapperCol: {
      offset: 0,
      span: 24,
    },
  };
// @connect装饰器
@connect(
    state=>({
        isLogin:state.userInfo.isLogin
    }), 
    {
        saveUserInfo:createSaveUserInfoAction
    }
) 
 class Login extends Component {
    state={
        userNum:'',
        password:'',
        isLogin:false
    }
    // 密码的验证器（自定义）
    pwdValidator = (rule,value) => {
        if(!value){
            // 提示密码必须输入
            return Promise.reject("提示密码必须输入");
        }
        else if(value.length>12){
            // 提示密码必须小于等于12位
            return Promise.reject("提示密码必须小于等于12位");
        }
        else if(value.length<4){
            // 提示密码必须大于等于4
        }else if(!(/^\w+$/).test(value)){
            // 提示密码必须有字母、数字、下划线组成
            return Promise.reject("提示密码必须有字母、数字、下划线组成");
        }else{
            return Promise.resolve();
        }
        return Promise.resolve();
    };

    onAdmin= async ()=>{
        let result= await reqLogin(this.userNum,this.password);
        const { code, data, msg } = result;
        if(code === 200){ //跳到admin
            // 服务器返回的user信息和token
            this.props.saveUserInfo(data)
            // 跳转
            this.props.history.replace('/training/home');
            
        }else{   //提示错误信息
            message.warning(msg,1)
        }
    }
    onTeacher = async ()=>{
        let result= await reqTeacherLogin(this.userNum,this.password);
        const { code, data, msg } = result;
        if(code === 200){ //跳到admin
            // 服务器返回的user信息和token
            this.props.saveUserInfo(data)
            // 跳转
            this.props.history.replace('/training/home');
            
        }else{   //提示错误信息
            message.warning(msg,1)
        }
    }

    userNumInput =(e)=>{
        this.userNum =e.target.value
    }
    passwordInput = (e)=>{
        this.password = e.target.value
        console.log(e.target.value);
    }
    render(){
        const { isLogin } = this.props
        if(isLogin){
            return <Redirect to='/training/home' />
        }else{
            return (
                <div className="login">
                    <header>
                        <img src={logo} alt="logo"/>
                        <h1>培训机构管理系统</h1>
                    </header>
                    <section>
                        <h1>用户登录</h1>
                        <h2>
                            <Form
                                {...layout}
                                name="basic"
                                initialValues={{
                                    remember: true,
                                }}
                                onFinish={false}
                                onFinishFailed={this.onFinishFailed}
                            >
                                <Form.Item
                                    label="用户名"
                                    name="userNum"
                                    rules={[
                                    {required: true,message: '用户名必须输入！',},
                                    // 声明式验证
                                    {max: 12,message: '用户名必须小于等于12位',},
                                    {min: 4,message: '用户名必须大于等于4位',},
                                    {pattern: /^\w+$/,message: '用户名只能由英文数字下划线组成',},
                                    ]}
                                >
                                    <Input onChange={this.userNumInput}/>
                                </Form.Item>
    
                                <Form.Item
                                    label="密 &nbsp;&nbsp;&nbsp;码"
                                    name="password"
                                    rules={[
                                        // 自定义验证 
                                    {required: true,message: '',},
                                    {validator:this.pwdValidator},
                                    ]}
                                >
                                    <Input.Password onChange={this.passwordInput}/>
                                </Form.Item>
    
                                <Form.Item {...tailLayout}>
                                    <Button type="primary"   onClick={this.onTeacher} className="login-from-admin">
                                        讲师登录
                                    </Button>
                                    <Button  type="primary"   onClick={this.onAdmin} className="login-from-teacher">
                                        管理员登录
                                    </Button>
                                </Form.Item>
                            </Form>
                        </h2>
                       
                    </section>
                </div>
            );
        }

    }
}
export default Login;
// 简写
/* export default connect(
    state=>({
        isLogin:state.userInfo.isLogin
    }), 
    {
        saveUserInfo:createSaveUserInfoAction
    }
)(Login); */

/* const mapStateToProps = (state) =>{
    const { test } = state
    console.log(test.test1);
    return{

    }
};
const mapDispatchToProps =(dispatch) =>{
    return{
        saveUserInfo =() =>{
            dispatch(createSaveUserInfoAction())
        }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Login); */